//
//  KLiveCollectionViewCell.m
//  Keping
//
//  Created by 柯平 on 2017/9/2.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KLiveCollectionViewCell.h"
#import "KCCTVsData.h"
#import <IJKMediaFramework/IJKMediaFramework.h>

@interface KLiveCollectionViewCell ()

@property (nonatomic,strong) UIActivityIndicatorView *activityIndicatiorView;

@property(nonatomic,strong)IJKFFMoviePlayerController* player;

@end

@implementation KLiveCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

-(UILabel *)timeLabel
{
    if (!_timeLabel) {
        _timeLabel = [UILabel new];
        _timeLabel.textColor = kWhiteColor;
        _timeLabel.textAlignment = NSTextAlignmentRight;
        _timeLabel.font = kFont(12);
        _timeLabel.frame = CGRectMake(5, 5, self.contentView.width-10, 20);
        [self.contentView addSubview:_timeLabel];
    }
    return _timeLabel;
}

-(UILabel *)placeLabel
{
    if (!_placeLabel) {
        _placeLabel = [UILabel new];
        _placeLabel.textColor = kWhiteColor;
        _placeLabel.font = kFont(12);
        _placeLabel.frame = CGRectMake(5, self.contentView.height-25, self.contentView.width-10, 20);
        [self.contentView addSubview:_placeLabel];
    }
    return _placeLabel;
}

-(void)layoutSubviews
{
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(5);
        make.right.mas_equalTo(-5);
        make.height.mas_equalTo(20);
    }];
    [self.placeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.right.bottom.mas_equalTo(-5);
        make.height.mas_equalTo(20);
    }];
}

-(void)setCctvObj:(KCctvEntityView *)cctvObj
{
    if (!cctvObj) return;
    _cctvObj = cctvObj;
    if (_player) {
        [_player shutdown];
        [_player.view removeFromSuperview];
        _player = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    if (_activityIndicatiorView) {
        [_activityIndicatiorView removeFromSuperview];
        _activityIndicatiorView = nil;
    }
    
    
    IJKFFOptions* options = [IJKFFOptions optionsByDefault];
    [options setPlayerOptionIntValue:1 forKey:@"videotoolbox"];
    //[options setPlayerOptionValue:@"1" forKey:@"videotoolbox"];
    [options setFormatOptionValue:@"tcp" forKey:@"rtsp_transport"];
    //[options setPlayerOptionValue:@"1" forKey:@"an"];
    [options setPlayerOptionIntValue:29.97 forKey:@"r"];
    [options setPlayerOptionIntValue:512 forKey:@"vol"];
    
    IJKFFMoviePlayerController *player = [[IJKFFMoviePlayerController alloc] initWithContentURLString:cctvObj.id withOptions:options];
    player.view.frame = self.contentView.bounds;
    player.scalingMode = IJKMPMovieScalingModeAspectFit;
    player.shouldAutoplay = NO;
    player.shouldShowHudView = NO;
    [self.contentView addSubview:player.view];
    [player.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    _player = player;
    __block UIActivityIndicatorView *activityIndicatior = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 32.0, 32.0)];
    [activityIndicatior setCenter:player.view.center];
    [activityIndicatior setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatior.hidesWhenStopped = YES;
    [player.view addSubview:activityIndicatior];
    _activityIndicatiorView = activityIndicatior;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [player prepareToPlay];
        [activityIndicatior startAnimating];
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didFinish) name:IJKMPMoviePlayerPlaybackDidFinishNotification object:_player];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stateDidChange) name:IJKMPMoviePlayerLoadStateDidChangeNotification object:_player];
}

-(void)didFinish
{
    if (_player.loadState & IJKMPMovieLoadStateStalled) return;
    if (![KAppConfig sharedConfig].networkStatus) {
        [_player shutdown];
        [_player.view removeFromSuperview];
        _player = nil;
        [_activityIndicatiorView stopAnimating];
    }
}

-(void)dealloc
{
    if (_player) {
        [_player shutdown];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        _activityIndicatiorView = nil;
        _player = nil;
    }
}

-(void)stateDidChange
{
    WEAKSELF
    if ((_player.loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        if (!_player.isPlaying) {
            [_player play];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_activityIndicatiorView stopAnimating];
            });
        }else{
            //网络不好
            dispatch_async(dispatch_get_main_queue(), ^{
                [_activityIndicatiorView startAnimating];
            });
        }
    }else if (_player.loadState & IJKMPMovieLoadStateStalled){
        //网络不加，自动暂停
        dispatch_async(dispatch_get_main_queue(), ^{
            [_activityIndicatiorView startAnimating];
        });
    }
}


@end
